<template>
  <div class="home-container">
    <!-- 第一行：折线图和饼图 -->
    <div class="charts-row">
      <div class="chart-container">
        <div class="chart-header">
          <span>医疗废物每日统计</span>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
            @change="handleDateChange"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </div>
        <div class="chart-body" ref="chartContainer3"></div>
      </div>
      <div class="chart-container">
        <div class="chart-header">
          <span>医疗废物分类占比分布</span>
          <el-date-picker
            v-model="typesDateRange"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
            @change="handleTypesDateChange"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </div>
        <div class="chart-body" ref="chartContainer2"></div>
      </div>
    </div>
    <!-- 第二行：柱状图 -->
    <div class="chart-container">
      <div class="chart-header">
        <span>医疗废物分类数量统计</span>
        <!-- 使用与饼图相同的日期范围 -->
      </div>
      <div class="chart-body" ref="chartContainer1"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { onActivated, onMounted, ref, onBeforeUnmount } from 'vue'
import api from '../api/api'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import 'dayjs/locale/zh-cn'

export default {
  name: 'HomePage',
  setup() {
    const chartContainer1 = ref(null)
    const chartContainer2 = ref(null)
    const chartContainer3 = ref(null)
    const dateRange = ref(null)
    const typesDateRange = ref(null)
    let chart1 = null
    let chart2 = null
    let chart3 = null

    // 日期快捷选项
    const shortcuts = [
      {
        text: '最近7天',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
          return [start, end]
        }
      },
      {
        text: '最近30天',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
          return [start, end]
        }
      }
    ]

    // 格式化日期
    const formatDate = (date) => {
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }

    // 处理每日统计日期变化
    const handleDateChange = async (value) => {
      try {
        if (!value) {
          // 如果清除日期，默认显示最近7天
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
          await fetchDailyData(formatDate(start), formatDate(end))
        } else {
          await fetchDailyData(value[0], value[1])
        }
      } catch (error) {
        console.error('处理日期变化失败:', error)
      }
    }

    // 处理分类统计日期变化
    const handleTypesDateChange = async (value) => {
      try {
        if (!value) {
          // 如果清除日期，默认显示最近7天
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
          await fetchWasteTypeData(formatDate(start), formatDate(end))
        } else {
          await fetchWasteTypeData(value[0], value[1])
        }
      } catch (error) {
        console.error('处理类型统计日期变化失败:', error)
      }
    }

    // 获取每日统计数据
    const fetchDailyData = async (startDate, endDate) => {
      try {
        console.log('请求每日统计参数:', { startDate, endDate })
        const response = await api.getDailyStatistics(startDate, endDate)
        console.log('每日统计数据响应:', response)
        
        if (response && typeof response === 'object') {
          updateDailyChart(response, startDate, endDate)
        } else {
          console.error('无效的响应数据:', response)
        }
      } catch (error) {
        console.error('获取每日统计数据失败:', error)
      }
    }

    // 获取废物类型统计数据
    const fetchWasteTypeData = async (startDate, endDate) => {
      try {
        console.log('请求废物类型统计参数:', { startDate, endDate })
        const response = await api.getWasteTypeStatistics(startDate, endDate)
        console.log('废物类型统计数据响应:', response)
        
        if (response && typeof response === 'object') {
          updateTypesCharts(response)
        } else {
          console.error('无效的响应数据:', response)
        }
      } catch (error) {
        console.error('获取废物类型统计数据失败:', error)
      }
    }

    // 更新每日统计图表
    const updateDailyChart = (data, startDate, endDate) => {
      try {
        if (!data || typeof data !== 'object') {
          console.error('无效的图表数据:', data)
          return
        }

        // 使用传入的日期范围生成所有日期
        const dates = []
        const start = new Date(startDate)
        const end = new Date(endDate)
        
        // 生成日期范围内的所有日期
        for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
          const dateStr = formatDate(d)
          dates.push(dateStr)
        }

        // 填充数据，没有数据的日期填充0
        const counts = dates.map(date => data[date] || 0)
        
        console.log('处理后的数据:', { dates, counts })

        const option = {
          title: {
            text: '医疗废物每日识别数量统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: function(params) {
              return `${params[0].axisValue}<br/>识别数量：${params[0].value}`
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
              rotate: 45,
              formatter: function(value) {
                return value.substring(5)  // 统一显示月-日
              },
              interval: dates.length > 30 ? 'auto' : 0  // 超过30天时自动间隔
            }
          },
          yAxis: {
            type: 'value',
            name: '识别数量',
            minInterval: 1
          },
          series: [{
            data: counts,
            type: 'line',
            smooth: true,
            lineStyle: {
              color: '#1890ff',
              width: 2
            },
            symbol: 'circle',
            symbolSize: 8,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgba(24,144,255,0.3)'
                },
                {
                  offset: 1,
                  color: 'rgba(24,144,255,0.1)'
                }
              ])
            }
          }]
        }
        
        if (chart3) {
          chart3.setOption(option)
        } else {
          console.error('图表实例未初始化')
        }
      } catch (error) {
        console.error('更新每日统计图表失败:', error)
      }
    }

    // 更新废物类型统计图表（饼图和柱状图）
    const updateTypesCharts = (data) => {
      try {
        if (!data || typeof data !== 'object') {
          console.error('无效的图表数据:', data)
          return
        }

        const categories = Object.keys(data)
        const values = Object.values(data)
        
        // 将数据组合并按数值从大到小排序
        const combinedData = categories.map((category, index) => {
          return {
            category: category,
            value: values[index]
          }
        }).sort((a, b) => b.value - a.value)
        
        // 从排序后的数据中提取类别和值
        const sortedCategories = combinedData.map(item => item.category)
        const sortedValues = combinedData.map(item => item.value)
        
        // 更新柱状图
        const option1 = {
          title: {
            text: '医疗废物分类数量统计（实际个数）',
            left: 'center',
            top: 10,
            textStyle: {
              fontSize: 18,
              fontWeight: 'bold'
            },
            subtext: `显示${typesDateRange.value ? typesDateRange.value[0] + '至' + typesDateRange.value[1] : ''}时间范围内各类型废物的具体数量`,
            subtextStyle: {
              fontSize: 14,
              color: '#666'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: function(params) {
              const total = sortedValues.reduce((sum, val) => sum + val, 0);
              const percent = ((params[0].value / total) * 100).toFixed(2);
              return `${params[0].name}<br/>数量：${params[0].value}个<br/>占比：${percent}%`;
            }
          },
          xAxis: {
            type: 'category',
            data: sortedCategories,
            axisLabel: { interval: 0, rotate: 30 }
          },
          yAxis: {
            type: 'value',
            name: '数量（个）',
            minInterval: 1
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '15%',
            top: '30%', // 增大顶部空间，为标题和总计留出足够位置
            containLabel: true
          },
          series: [{
            data: sortedValues,
            type: 'bar',
            barWidth: '40%',
            label: {
              show: true,
              position: 'top',
              formatter: '{c}个',
              fontSize: 14
            },
            itemStyle: { 
              color: function(params) {
                // 使用与饼图一致但深度不同的颜色
                const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de'];
                return colors[params.dataIndex % colors.length];
              }
            }
          }]
        };
        
        // 添加总计数字的显示
        const total = sortedValues.reduce((sum, val) => sum + val, 0);
        option1.graphic = [{
          type: 'text',
          left: 'center',
          top: 60, // 放在标题和副标题的下方
          style: {
            text: `总计: ${total}个`,
            fontSize: 16,
            fontWeight: 'bold'
          }
        }];
        
        chart1.setOption(option1)

        // 更新饼图
        const pieData = categories.map((name, index) => ({
          name,
          value: values[index]
        }))
        
        const option2 = {
          title: {
            text: '医疗废物分类占比分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle'
          },
          series: [{
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {d}%'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            data: pieData
          }]
        }
        chart2.setOption(option2)
      } catch (error) {
        console.error('更新废物类型统计图表失败:', error)
      }
    }

    const initCharts = async () => {
      try {
        // 初始化图表实例
        chart1 = echarts.init(chartContainer1.value)
        chart2 = echarts.init(chartContainer2.value)
        chart3 = echarts.init(chartContainer3.value)
        
        // 设置默认日期范围（最近7天）
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
        
        const startDateStr = formatDate(start)
        const endDateStr = formatDate(end)
        
        // 设置日期选择器的默认值
        dateRange.value = [startDateStr, endDateStr]
        typesDateRange.value = [startDateStr, endDateStr]
        
        // 获取数据并初始化图表
        await Promise.all([
          fetchDailyData(startDateStr, endDateStr),
          fetchWasteTypeData(startDateStr, endDateStr)
        ])
      } catch (error) {
        console.error('初始化图表失败:', error)
      }
    }

    onActivated(() => {
      initCharts()
      window.addEventListener('resize', handleResize)
    })

    const handleResize = () => {
      chart1?.resize()
      chart2?.resize()
      chart3?.resize()
    }

    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize)
      chart1?.dispose()
      chart2?.dispose()
      chart3?.dispose()
    })

    return {
      chartContainer1,
      chartContainer2,
      chartContainer3,
      dateRange,
      typesDateRange,
      shortcuts,
      handleDateChange,
      handleTypesDateChange,
      locale: zhCn
    }
  }
}
</script>

<style scoped>
.home-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.charts-row {
  display: flex;
  gap: 20px;
  width: 100%;
  min-height: 400px;
}

.chart-container {
  flex: 1;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-body {
  flex: 1;
  width: 100%;
  min-height: 350px;
}

.chart-header :deep(.el-range-editor) {
  width: 350px;
}
</style>